<?php

/*
    Open Designs Content Management System (odCMS)
    Copyright (C) 2010  Thomas Wong - tom@ztml.org

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
*/

class contentUpdate extends contentControl

{
	/*----------------\
	| update contents |
	\----------------*/
	function contentUpdate()
	{
		$this->contentControl();	
	}

        /*----------------\
        | process updates |
        \----------------*/
	function procUpdates()
	{
		if($_REQUEST['Update']=="Forum")
		{
			$this->updateForum();
			exit;
		}
		if($_REQUEST['Update']=="listing")
		{
			$this->updateListing();
			exit;
		}
		//echo "(".$_SESSION['CWD'].") ($this->cwd) (".$_SESSION['UserName'].")";exit;
		if(!$_SESSION['UserName'] || $this->cwd != $_SESSION['CWD'])
		{
			if($_POST['document'] != "_notes_" && $_REQUEST['utype'] != "comment")
			{
				$this->opUdfMessage("udf_040"); // login required
				exit;
			}
		}
		if($_SESSION['UserName']) $this->_CC_['member'] = $_SESSION['UserName'];

		switch($_REQUEST['Update'])
		{
			case 'Listing':
				$this->updateThisListing();
				exit;

			case 'attachment':
				$this->opForm("attachment");
				exit;

			case 'user':
				$this->updateUser();
				exit;

			case 'profile':
				if($_POST['Save']) $this->updProfile();
				$this->showProfile();
				break;

			case 'menu':
				$this->updateMenu();
				break;

			case 'theme':
				if($_POST['Save']) $this->saveTheme();
				$this->updateTheme();
				break;

			case 'Table':
				$this->updateTable();
				break;

			case 'gallery':
				$this->updateGallery();
				break;

			case 'Blog':
				$this->updateBlog();
				exit;

			case 'Forum':
				$this->updateForum();
				exit;

			case 'WDN':
				$this->updateWDN();
				exit;

			case 'Mail':
				$this->procMailMsgs();
				echo $this->_CC_['content'];
				exit;

			case 'points':
				$this->updatePoints();
				exit;
				
			case 'content':
				if($_REQUEST['document'])
				{
					$this->updateDocument();
					exit;
				}
				$this->updateContent();
				break;
				
			case 'odcms':
				if($_SESSION['UserName']!="admin")
				{
					$this->opUdfMessage("udf_027"); // admin login require
					exit;			
				}

				if($_REQUEST['dtype'] == "msgs") $this->_CC_['odcms'] = "Messages";
				elseif($_REQUEST['dtype'] == "frms") $this->_CC_['odcms'] = "Forms";
				elseif($_REQUEST['dtype'] == "strs") $this->_CC_['odcms'] = "Strings";
				else
				{
					$this->opUdfMessage("udf_037"); // invalid template
					exit;
				}
				if($_POST['Save']) $this->saveCmsTemplates($_REQUEST['dtype']);
				$this->updateCmsTemplates($_REQUEST['dtype']);
				break;

		}
		$this->opForm("odcms_cpanel");

		exit;
	}
	
        /*----------------\
        | show profile |
        \----------------*/
        function showProfile()
        {
		$this->getProfile();
		$this->_CC_['User'] = $this->username;
		$this->getSelectList($this->_CC_['editor'],$this->_CC_['template']);
                $this->opForm("odcms_profile");
                exit;
        }

        /*---------------\
        | update profile |
        \---------------*/
        function updProfile() 
        {
		if($_POST['new'])
		{
			$password = crypt($_POST['password'],$this->username);
			if($this->_CC_['password']!=$password )
			{
				$this->opUdfMessage("udf_010"); //Invalid Password!
				exit;
			}
			if($_POST['new'] != $_POST['again'])
			{
				$this->opUdfMessage("udf_011"); //Passwords don't match!
				exit;				
			}
			$this->_CC_['password'] = crypt($_POST['new'],$this->username);
		}
		$this->updateProfile();
		
		if($_POST['mode']=="edit")
		{
			$this->_CC_['page'] = "?Page=_profile_";
			$this->opMessage("reload_page");
		}
		else	$this->opMessage("lytebox_close");
		
		exit;
	}

        /*--------------------\
        | update user profile |
        \--------------------*/
	function updateProfile()
	{
		$uid  = $this->username;
		$path = "./users/$uid/images/";
		if($_FILES['logo']['tmp_name'])
		{
			$this->resizeImage($_FILES['logo']['tmp_name'],0,$path."full",$path."thumb",1);
		}
		if($_FILES['icon']['name'])
		{
			move_uploaded_file($_FILES['icon']['name'], $path."favicon.ico");
		}

		$about    = sqlite_escape_string(stripslashes( $_POST['about'] ));
		$meta     = sqlite_escape_string(stripslashes( $_POST['meta'] ));
		$city     = sqlite_escape_string(stripslashes( $_POST['city'] ));
		$fname    = sqlite_escape_string(stripslashes( $_POST['fname'] ));
		$lname    = sqlite_escape_string(stripslashes( $_POST['lname'] ));
		$cname    = sqlite_escape_string(stripslashes( $_POST['cname'] ));
		$ctitle   = sqlite_escape_string(stripslashes( $_POST['ctitle'] ));
		$slogan   = sqlite_escape_string(stripslashes( $_POST['slogan'] ));
		$copyr    = sqlite_escape_string(stripslashes( $_POST['copyright'] ));
		$state    = $_POST['state'];
		$email    = $_POST['email'];
		$emode    = $_POST['emode'];
		$editor   = $_POST['editor'];
		
		$template = $_POST['template'];
		
		$password = $this->_CC_['password'];
		if($password)
		{
			$password = "Password='$password', ";
		}
		if($email)
		{
			$q = $this->MEMBERS->query("SELECT ID FROM members WHERE eMail='$email' AND ID!='$uid'");
			list($uname) = $q->fetch();
			if($uname)
			{
				echo "$email is already used by another member!";
				exit;
			}
			$email = "eMail='$email', ";
		}
		if($editor)
		{
			$editor = "Editor='$editor',";
		}
		if($template)
		{
			if($template=="NONE") $template = "";
			$template = "Template='$template',";
		}

		$emode = "eMode='$emode',";
		
		$zip5 = $_POST['zip5'];
		$zip4 = $_POST['zip4'];
		$zip  = $zip5;
		if($zip4) $zip .= "-$zip4";
		$mdate = $this->_CC_['datetime'];
		$this->MEMBERS->query("UPDATE members SET $email Name='$fname $lname',Profile='$about',Organization='$cname',".
				      "State='$state',City='$city',Zip='$zip',District='$dist' WHERE ID='$uid'");
		$this->UDB->query("UPDATE _profile_ SET $password$email$editor$emode$template fName='$fname',lName='$lname',".
				      "City='$city',State='$state',Zip='$zip',District='$dist',About='$about^^^^^$meta',".
				      "cName='$cname',cTitle='$ctitle',Slogan='$slogan',copyRight='$copyr',mDate='$mdate' ".
				      "WHERE uName='$this->username'");
		if($this->_CC_['USITE']!="_main" && $this->username == "admin")
		{
			$q  = new SQLiteDatabase("../_main/members.dbf"); // main site members database
			$id = substr($this->_CC_['USITE'], 1);
			$q->query("UPDATE members SET $email Name='$fname $lname',Profile='$about',Organization='$cname',".
				      "State='$state',City='$city',Zip='$zip',District='$dist',mDate='$mdate' WHERE ID='$id'");
		}
		$_SESSION['theme'] = $template;

		return;
	}

	/*----------------\
        | update document |
        \----------------*/
        function updateDocument()
        {
		if ($_POST['Close'])
		{
			$this->opMessage("lytebox_close");
			exit;
		}
		if($_POST['Save'])
		{
			if($_POST['Save']=="Save" || $_POST['Save']=="Update" || $_POST['Save']=="Add") $this->saveDocument();
			exit;
		}
		$q = @$this->UDB->query("SELECT * FROM Document WHERE cid='".$_REQUEST['document']."'");
		if ($q === false)
		{
			echo "Error reading database file";
			exit;
		}
		list($title,$cid,$type,$header,$content) = $q->fetch();

		$this->_CC_['header']  = stripslashes($header);
		$this->_CC_['content'] = stripslashes($content);

		$this->_CC_['header']  = preg_replace("/&/","&amp;",$this->_CC_['header']);
		$this->_CC_['header']  = preg_replace("/</","&lt;",$this->_CC_['header']);			
		$this->_CC_['header']  = preg_replace("/\"/","'",$this->_CC_['header']);			
		$this->_CC_['content'] = preg_replace("/&/","&amp;",$this->_CC_['content']);
		$this->_CC_['content'] = preg_replace("/</","&lt;",$this->_CC_['content']);			

		$this->opForm("edit_section");

		exit;
        }

        /*--------------\
        | save Document |
        \--------------*/
        function saveDocument()
        {
		if($_POST['TYPE'])
		{
			$content = sqlite_escape_string(stripslashes($_POST['content']));
			$this->UDB->query("UPDATE Document SET Header='".$_POST['header']."', Content='$content' WHERE cid='".$_POST['document']."'");
			if($this->_CC_['flag'])
			{
				$this->opMessage("lytebox_close");
				exit;
			}
			$this->_CC_['page'] = "?Update=attachment";
			$this->opMessage("reload_page");
			exit;
		}
		if($_POST['new_page'])
		{
			$q = @$this->UDB->query("SELECT cid FROM Document ORDER BY cid DESC");
			list($cid) = $q->fetch();
			$cid++;
			$q = $this->UDB->query("INSERT INTO Document VALUES('attachment.$cid','$cid','Attachment','".
					       $_POST['new_page']."','Please update the content...','".$this->_CC_['datetime']."')");
		}
		else
		{
			for($ix=0;$ix<=$this->_CC_['count'];$ix++)
			{
				if($this->_CC_["delete_$ix"])
				{
					$this->UDB->query("DELETE FROM Document WHERE cid='".$this->_CC_["delete_$ix"]."'");
				}
			}
		}
		$this->_CC_['page'] = "?Update=attachment";
		$this->opMessage("reload_page");
		exit;
	}
	
        /*-------------\
        | update theme |
        \-------------*/
	function updateTheme()
	{
		if($_POST['Delete']=="Delete")
		{
			if($this->deleteTheme($_POST['tpl']))
			{
				$this->opUdfMessage("udf_022"); // Theme deleted
				exit;
			}
		}
		if($_POST['designer']) return $this->createTheme();
		
		if(!$_POST['tpl'] || $_POST['tpl']=="Select" )
		{
			$this->getDesignersSelectList();
			$this->getSelectList("","Select");

			$this->opForm("theme_select");

			exit;
		}
		if($this->_CC_['Preview'])
		{
			$this->_CC_['page'] = "?theme=".$_REQUEST['tpl']."&preview=1";
			$this->opMessage("reload_page");
			exit;
		}

		$this->_CC_['content'] = $this->getTheme($_POST['tpl']);

		if(!$this->_CC_['content'])
		{
			$this->_CC_['FileName'] = $_POST['tpl'];
			$this->opUdfMessage("udf_036"); // error read template
			exit;
		}
		list($this->_CC_['header'],$this->_CC_['body']) = explode("^^^^^",$this->_CC_['content'],2);
		$this->_CC_['header'] = stripslashes($this->_CC_['header']);
		$this->_CC_['body']   = stripslashes($this->_CC_['body']);
		$this->_CC_['body']   = preg_replace("/<title>(.*)<\/title>/","<title>{title}</title>",$this->_CC_['body']);
		$this->_CC_['body']   = preg_replace("/<\/textarea/","&lt;/textarea",$this->_CC_['body']);
		$this->_CC_['body']   = preg_replace("/<textarea/","&lt;textarea",$this->_CC_['body']);
		
		$this->opForm("theme_update");
		
		exit;
	}
	
        /*-----------\
        | save theme |
        \-----------*/
	function saveTheme()
	{
		if($_POST['act']=="Select" ) return $this->updateTheme();
		
		//$content = stripslashes($_POST['header'])."^^^^^\n".stripslashes($_POST['content']);
		$content = $_POST['header']."^^^^^\n".$_POST['content'];
		$this->saveMemberData($_POST['tpl'].".tpl",$content);
		
		$this->opUdfMessage("udf_023"); // Theme updated
		exit;
	}
		
        /*-----------------\
        | create new theme |
        \-----------------*/
	function createTheme()
	{
		if(!$_POST['design'])
		{
			$this->getDesignsSelectList($_POST['designer']);
			$this->opForm("theme_add");
			exit;
		}
		if($this->getTheme($_POST['designer']."_".$_POST['design']))
		{
			echo $_POST['designer']."_".$_POST['design'].
					" is already converted<br /><br />
			<input type='button' value='Back' onclick='javascript:history.go(-2)' />";
			exit;
		}
		$this->copyTheme($_POST['designer'],$_POST['design']);
		
		$this->_CC_['header'] = "set: DIR=../designs/".$_POST['designer']."/".$_POST['design']."/\n".
					$this->getTplValue("strs","udf_092");
		
		$this->_CC_['body'] = $this->getDesign($_POST['designer'],$_POST['design']);
		$this->_CC_['body'] = preg_replace("/<title>(.*)<\/title>/","{META}\n<title>{title}</title>",$this->_CC_['body']);
		$this->_CC_['body'] = preg_replace("/import \"/","import \"{DIR}",$this->_CC_['body']);
		$this->_CC_['body'] = preg_replace("/src=\"/","src=\"{DIR}",$this->_CC_['body']);
		$this->_CC_['body'] = preg_replace("/href=\"/","href=\"{DIR}",$this->_CC_['body']);
		$this->_CC_['body'] = preg_replace("/<\/textarea/","&lt;/textarea",$this->_CC_['body']);
		$this->_CC_['body'] = preg_replace("/<textarea/","&lt;textarea",$this->_CC_['body']);

		$this->_CC_['body']  = preg_replace("/\{DIR\}http/","http",$this->_CC_['body']);
		$this->_CC_['body'] .= "\n{lstatus} {poweredby}\n";
		
		$this->_CC_['tpl'] = $_POST['design'];
		
		$this->opForm("theme_update");
		
		exit;
	}

        /*--------------------\
        | copy theme template |
        \--------------------*/
	function copyTheme($designer,$design)
	{	
		$this->_CC_['content'] = file_get_contents("../templates/$designer/$design.tpl");

		if(!$this->_CC_['content']) return;

		list($this->_CC_['header'],$this->_CC_['body']) = explode("^^^^^",$this->_CC_['content'],2);
		$this->_CC_['header'] = stripslashes($this->_CC_['header']);
		$this->_CC_['body']   = stripslashes($this->_CC_['body']);
		$this->_CC_['body']   = preg_replace("/<title>(.*)<\/title>/","<title>{title}</title>",$this->_CC_['body']);
		$this->_CC_['body']   = preg_replace("/<\/textarea/","&lt;/textarea",$this->_CC_['body']);
		$this->_CC_['body']   = preg_replace("/<textarea/","&lt;textarea",$this->_CC_['body']);

		$this->_CC_['tpl'] = $design;
		
		$this->opForm("theme_update");
		
		exit;
	}
	
        /*-------------------\
        | get theme template |
        \-------------------*/
	function getTheme($template)
	{	
		return @file_get_contents("./users/$this->username/$template.tpl");
	}
	
        /*----------------------\
        | delete theme template |
        \----------------------*/
	function deleteTheme($template)
	{		
		return @unlink("./users/$this->username/$template.tpl");
	}
	
        /*---------------\
        | update gallery |
        \---------------*/
	function updateGallery()
	{
		switch($_REQUEST['action'])
		{
			case 'upload':
				$this->uploadGallery();
				break;
			case 'delete':
				$this->updateFile($_REQUEST['action']);
				break;
			case 'update':
				$this->updateFile($_REQUEST['action']);
				exit;
		}
		exit;
	}

        /*------------\
        | upload file |
        \------------*/
	function uploadGallery()
	{
		if($_GET['action'])
		{
			$this->opForm("gallery_upload");
		}
		else
		{
			$this->uploadFile($_POST['album']);
		}
		exit;
	}
	
        /*------------\
        | upload file |
        \------------*/
	function uploadFile($folder)
	{
		if(!$folder)
		{
			$this->opUdfMessage("udf_057"); // missing folder name
			return 0;
		}
		
		$ifile = $_FILES['file']['tmp_name'];
		$this->_CC_['folder'] = $folder;
		$this->_CC_['fname'] = $_FILES['file']['name'];

		$path = "./users/$this->username/images/$folder/";

		$full  = $path.$this->_CC_['fname'];
		$thumb = $path."_".$this->_CC_['fname'];
		$ftype = 0;

		$q = @$this->UDB->query("SELECT Album FROM Albums WHERE Name='".$this->_CC_['fname']."'");
		list($album) = $q->fetch();
		if($album)
		{
			echo "Photo ".$this->_CC_['fname']." has already been uploaded into folder $album";
			exit;
		}

		if($this->_CC_['url'])
		{
			$ftype++;
			$this->_CC_['fname'] = $this->_CC_['datetime'];
			$ifile = $path."temp";

			$data = @file_get_contents($this->_CC_['url']);
			if(!$data)
			{
				$this->opUdfMessage("udf_075"); // null content
				exit;
			}
			$fp = fopen($ifile,"w");
			fwrite($fp,$data);
			fclose($fp);
			$full  = $path.$this->_CC_['datetime'];
			$thumb = $path."_".$this->_CC_['datetime'];
		}
		elseif(file_exists  ( $path.$this->_CC_['fname'] ))
		{echo "$path".$_FILES['file']['name'].")(".$_FILES['file']['name'].") file was already uploaded";exit;
			$this->opUdfMessage("udf_053"); // file was already uploaded
			exit;
		}		

		if(! $this->resizeImage($ifile,$_POST['resize'],$full,$thumb,$ftype))
		{echo "can't resize image";
			$this->opUdfMessage("udf_058"); // can't resize image
			exit;
		}

		$this->_CC_['status'] = $this->addAlbumList($this->_CC_['aid'],$this->_CC_['fname'],$_POST['uname'],$_POST['desc'],$folder);
		$this->opUdfMessage("udf_054"); // file uploaded sucessfully

		$this->_CC_['page'] = "?Gallery=$folder";
		$this->opMessage("reload_page");
		exit;
	}
		
        /*----------------------\
        | add new photo to list |
        \----------------------*/
	function addAlbumList($aid,$aname,$uname,$desc,$folder) // aname=system assigned name, uname=user assigned name
	{
		if(!$aid)
		{
			$q = @$this->UDB->query("SELECT aid FROM Albums ORDER BY aid DESC");
			list($aid) = $q->fetch();
			$aid++;
		}
		else
		{
			$q = @$this->UDB->query("SELECT Name,Title FROM Albums WHERE aid='$aid'");
			list($name,$title) = $q->fetch();
			if($name)
			{
				echo "ID $aid is already assigned: $name, $title";
				exit;
			}
		}
		$desc  = sqlite_escape_string(stripslashes($desc));
		$cmnt  = sqlite_escape_string(stripslashes($cmnt));
		$aname = sqlite_escape_string(stripslashes($aname));
		$uname = sqlite_escape_string(stripslashes($uname));

		$q = $this->UDB->query("INSERT INTO Albums VALUES('$aname','$aid','$folder','$uname','$desc^^^$cmnt','".
				       $this->_CC_['datetime']."')");
		if(!$q)
		{
			$this->opUdfMessage("udf_047"); // Can't upate albums
			exit;
		}
	
		$this->_CC_['content_name'] = $aname;
		return $this->getUdfMsg("udf_048"); // new item added into the list
	}

	/*---------------\
        | delete gallery |
        \---------------*/
	function deleteGallery($folder)
	{
		$q = $this->UDB->query("SELECT COUNT(*) FROM Albums WHERE Album='$folder'");
		if ($q === false)
		{
			echo "ERROR reading album";
			exit;
		}
		list($this->_CC_['total']) = $q->fetch();
				
		if($this->_CC_['total'])
		{
			$this->opUdfMessage("udf_049"); // album not empty
			exit;
		}
		$this->unlinkRecursive("./users/$this->username/images/$folder/");
	}
	
        /*------------\
        | update file |
        \------------*/
	function updateFile($utype)
	{
		list($folder,$fname) = explode(".",$this->_CC_['album'],2);
		$aid = $_POST['id'];
		if($utype=="delete")
		{
			$q = @$this->UDB->query("DELETE FROM Albums WHERE Album='$folder' AND Name='$fname'");
			if ($q === false)
			{
				echo "(DELETE FROM Albums WHERE Album='$folder' AND Name='$fname') <br />Error updating $table where ID=$aid";
				exit;
			}
			$path = "./users/$this->username/images/$folder";
			@unlink("$path/$fname"); @unlink("$path/_$fname");

			$this->_CC_['fname'] = "$path/$fname";
				
			$this->opUdfMessage("udf_055"); // file deleted
		}
		else
		{
			$name = sqlite_escape_string(stripslashes($_POST['uname']));
			$desc = sqlite_escape_string(stripslashes($_POST['desc']));
			$cmnt = sqlite_escape_string(stripslashes($_POST['cmnt']));
			$q = @$this->UDB->query("UPDATE Albums SET Title='$name', aid='$aid', Description='$desc$cmnt', mdate='".$this->_CC_['datetime'].
						"' WHERE Album='$folder' AND Name='$fname'");
			if ($q === false)
			{
				echo "UPDATE Albums SET Title='$name', Description='$desc', mdate='".$this->_CC_['datetime'].
						"' WHERE Album='$folder' AND aid='$aid' <br />Error updating $table where ID=$rnum";
				exit;
			}
			$this->opMessage("close_window"); // file updated
		}

		if($utype=="delete") $this->_CC_['page'] = "?Gallery=$folder";
		else $this->_CC_['page'] = "?use=gallery_display&show=$this->username.$folder.$aid";
		$this->opMessage("reload_page");
		exit;
	}

	/*---------------------\
        | save odCMS templates |
        \---------------------*/
	function saveCmsTemplates($table)
	{
		if($_REQUEST['Save'] == "Close")
		{
			$this->opMessage("lytebox_close");
			exit;
		}
		if($_POST['tname']) return $this->updateCmsData($table,$_POST['tname']);
		
		$this->getCmsTemplateList($table,0);

		for($ix=0;$ix<$this->_CC_['count'];$ix++)
		{
			if(!$this->_CC_["name_$ix"]) continue;

			if ($this->_CC_["dlt_$ix"])
			{
				$this->deleteCmsData($table,$this->_CC_["name_$ix"]);
			}
		}

		if($_REQUEST['add'])
		{					
			$this->addCmsData();
		}

		$this->_CC_['page'] = "?Update=odcms&dtype=".$this->_CC_['dtype'];
		$this->opMessage("reload_page");
		
		exit;
	}
				
        /*----------------------------\
        | get odCMS templates listing |
        \----------------------------*/
	function getCmsTemplateList($table,$flag)
	{
		$q = @$this->TEMPLATES->query("SELECT * FROM $table ORDER BY tid");
		if ($q === false)
		{
			echo "Error reading table $table";
			exit;
		}
		$tlist = $this->getTplValue("strs","udf_091"); // Template list
		$this->_CC_['mvup'] = $this->_CC_['tlist'] = "";
		$this->_CC_['count'] = 0;
		$tnum = 1;
		while( $q->valid() )
		{
			list($name,$tid,$desc,$value) = $q->current();

			$this->_CC_['tid']  = $tid = trim($tid);
			$this->_CC_['name'] = $this->_CC_["name_$tid"] = trim($name);
			$this->_CC_['desc'] = $this->_CC_["desc_$tid"] = trim($desc);
			$this->_CC_["data_$tid"] = trim($value);
			if(!$this->_CC_["name_$tid"]) continue;
			
			if($flag)
			{
				if($tnum>1) $this->_CC_['mvup'] = "<a href='?Update=odcms&mvup=$tid&dtype=".$this->_CC_['dtype']."'>MoveUp</a>";
				$this->_CC_['tlist'] .= $this->subString($tlist);
			}
			$tnum++;
			
			$q->next();
		}
		$this->_CC_['count'] = $tid+1;
	}

        /*------------\
        | update user |
        \------------*/
	function updateUser()
	{
		if($_SESSION['UserName']!="admin")
		{
			$this->opUdfMessage("udf_027"); // admin login require
			exit;			
		}
		switch($_REQUEST['type'])
		{
			case 'password':
				$this->resetPassword();
				break;
			case 'delete':
				$this->deleteUser();
				break;
			default:
		}
		exit;
	}
		

        /*------------\
        | delete user |
        \------------*/
	function deleteUserDirs($uname)
	{
		$this->UDB = new SQLiteDatabase("./users/$uname/contents.dbf");
		$q = $this->UDB->query("SELECT Member,Points FROM transactions WHERE Activity='Signup'");
		list($member,$bonus) = $q->fetch();
					
		$q = $this->MEMBERS->query("SELECT points FROM members WHERE ID='$member'");
		list($points) = $q->fetch();
		$points-= $bonus;
		$this->MEMBERS->query("UPDATE members SET Points='$points' WHERE ID='$member'"); // give back bonus points
		
		$path = "./users/$uname";
		$this->removeDirectory($path);
		
		$this->MEMBERS->query("DELETE FROM members WHERE ID='$uname'");
		$this->MEMBERS->query("DELETE FROM activities WHERE UID='$uname'");
	}
	
        /*-----------------\
        | remove directory |
        \-----------------*/
	function removeDirectory($dir)
	{
		$this->_CC_['status'] =  "";
		$handle = @opendir($dir);
		if(!$handle)
		{
			$this->_CC_['status'] .= "<font color='red'>Unable to open $dir.</font><br /><br />";
			return;
		}
		while (false !== ($file = readdir($handle)))
		{
			if($file[0] == ".") continue;
			if(is_dir("$dir/$file")) $this->removeDirectory("$dir/$file");
			else
			{
				if(@unlink("./$dir/$file")) $this->_CC_['status'] .= "$dir/$file deleted.<br />";
			else $this->_CC_['status'] .= "<font color='red'>Error encountered deleting $dir/$file.</font><br />";
			}
		}
		if(@rmdir($dir)) $this->_CC_['status'] .= "Directory $dir/$file deleted.<br /><br />";
		else $this->_CC_['status'] .= "<font color='red'>Error encountered deleting directory $dir.</font><br /><br />";
	}

        /*--------------------\
        | reset user password |
        \--------------------*/
	function resetPassword()
	{
		if($_POST['reset'])
		{
			$uid = $_POST['reset'];
			$password = crypt($uid,$uid);
			$this->UDB->query("UPDATE _profile_ SET Password='$password' WHERE uName='$uid'");
			$this->_CC_['UserName'] = $uid;
			$this->opUdfMessage("udf_016"); //Passoword for {UserName} is reset
		}
		else
		{
			$this->_CC_['content'] = $this->getUserList("password");

			$this->opForm("reset_user");
		}
		exit;
	}

	/*-----------------\
        | delete user site |
        \-----------------*/
	function deleteUser()
	{
		if($_POST['delete'])
		{
			$this->deleteUserDirs($_POST['delete']);
			$this->opUdfMessage("udf_038"); //delete user status
			exit;
		}
		$this->_CC_['content'] = $this->getUserList("delete");

		$this->opForm("delete_user");
		exit;
	}

        /*-----------------\
        | get user listing |
        \-----------------*/
	function getUserList($type)
	{
		$content = "";
		
		$handle = opendir("./users/");
		while (false !== ($file = readdir($handle)))
		{
			if(!is_dir("./users/$file") || $file[0] == ".") continue;
			if($type=="delete")
			{
				if($file=="admin") continue;
			}
			$content .= "<option value='$file'>$file</option>";
		}
		closedir($handle);
		
		return $content;
	}

	/*------------------------\
        | check verification code |
        \------------------------*/
	function checkVerification()
	{
		$verif_box = $_POST['verif_box'];
		// check to see if verificaton code was correct
		$num = md5($verif_box).'a4xn';
		$cok = $_SESSION['rand_number'];
		if($num == $cok)
		{
			// delete the cookie so it cannot sent again by refreshing this page
			$_SESSION['rand_number'] = "";
			return 0;
		}
		return 1;
	}
		   
	/*-------------------------------\
        | Checks whether a design exists |
        \-------------------------------*/
	function designExists($design,$nitems,$lists)
	{
		for($ix=0;$ix<$nitems;$ix++)
		{
			list($item) = explode("\xf1",$lists[$ix]);

			if($item == $design)
			{
				echo "$ix: $design exists<br />";
				return 1;
			}
		}
		return 0;
	}
	
	/*----------------------\
        | get designs selection |
        \----------------------*/
	function getDesignsSelectList()
	{
		$this->_CC_['designs']  = "<option value=''>-Select-</option>\n";
		$designs = array();

		if ($handle = opendir("../designs/".$this->_CC_['designer']))
		{
			while (false !== ($file = readdir($handle)))
			{
				if(!is_dir("../designs/".$this->_CC_['designer']."/$file") || $file[0] == ".") continue;
				array_push($designs,$file);
			}
			closedir($handle);
		} 
		sort($designs);
		foreach ($designs as $key => $val)
		{
			$this->_CC_['designs'] .= "<option value='$val'>$val</option>";
		}
	}
			
        /*----------------------\
        | get design index file |
        \----------------------*/
	function getDesign($designer,$index)
	{
		return @file_get_contents("../designs/$designer/$index/index.html");
	}
	
	/*------------------------\
        | get designers selection |
        \------------------------*/
	function getDesignersSelectList()
	{
		$this->_CC_['designers']  = "<option value=''>-Select-</option>\n";
		$designers = array();
		if ($handle = opendir("../designs/"))
		{
			while (false !== ($file = readdir($handle)))
			{
				if(!is_dir("../designs/$file") || $file[0] == ".") continue;
				array_push($designers,$file);
			}
			closedir($handle);
		} 
		sort($designers);
		foreach ($designers as $key => $val)
		{
			$this->_CC_['designers'] .= "<option value='$val'>$val</option>";
		}
	}
	
        /*--------------------\
        | update page content |
        \--------------------*/
	function updateContent()
	{
		if($_POST['Update']) return $this->saveMemberContent($_POST['filename']);

		$this->getUserContent($this->_CC_['Page'],"update");
		
		$this->_CC_['header']  = preg_replace("/&/","&amp;",$this->_CC_['header']);
		$this->_CC_['header']  = preg_replace("/</","&lt;",$this->_CC_['header']);			
		$this->_CC_['content'] = preg_replace("/&/","&amp;",$this->_CC_['content']);
		$this->_CC_['content'] = preg_replace("/</","&lt;",$this->_CC_['content']);			

		$this->opMessage("update_content");

		exit;
	}

        /*--------------------\
        | update this listing |
        \--------------------*/
	function updateThisListing()
	{
		if($_REQUEST['remote'])
		{
			$site = $_REQUEST['remote'];
			$this->MEMBERS->query("INSERT INTO activities VALUES(NULL,'announcement','$site','".$_REQUEST['uname'].
					      "','updated announcement','?usite=$site','".$this->_CC_['datetime']."')");
			exit;
		}
		$username = $_SESSION['UserName'];
		if(!$username)
		{
			echo "Login Required!";
			exit;
		}
		$this->BLOG = new SQLiteDatabase("./users/$username/blog.dbf"); // user blog database

		$content = sqlite_escape_string(stripslashes($_POST['summary']))."^^^".
			   sqlite_escape_string(stripslashes($_POST['description']));
		$title   = sqlite_escape_string(trim($_POST['ltitle']));
		$credits = trim($_POST['credits']);

		if($_POST['delete'])
		{
			$this->BLOG->query("DELETE FROM blog WHERE bid='".$_POST['delete']."'");
			$rtnc = @file_get_contents("?usite=_announcements&Update=Listing&delete=1&sid=_members".
					   "&uid=$username&pname=Announcements&site=".$this->_CC_['DOMAIN']);
			$this->MEMBERS->query("INSERT INTO activities VALUES(NULL,'delete2','$this->username','".
					      $this->_CC_['fname']." ".$this->_CC_['lname'].
					      "','deleted announcement','?Page=Profile&member=$this->username','".$this->_CC_['datetime']."')");
		}
		elseif($_POST['edit'])
		{
			$this->BLOG->query("UPDATE blog SET Topic='$title',Website='$credits',Content='$content',".
					   "mdate='".$this->_CC_['datetime']."' WHERE bid='".$_POST['edit']."'");
			$this->MEMBERS->query("INSERT INTO activities VALUES(NULL,'announcement','$username','".
					      $this->_CC_['fname']." ".$this->_CC_['lname'].
					      "','updated announcement','?Page=My Announcement&member=$username','".$this->_CC_['datetime']."')");
		}
		else
		{
			$this->BLOG->query("INSERT INTO blog VALUES(NULL, '_listings_', '0', '0', ".
					   "'$username', '', '', ".
					   "'$title', '$content', '".$this->_CC_['datetime']."')");
			$this->MEMBERS->query("INSERT INTO activities VALUES(NULL,'announcement','$username','".
					      $this->_CC_['fname']." ".$this->_CC_['lname'].
					      "','added announcement','?Page=My Announcement&member=$username','".$this->_CC_['datetime']."')");
		}
		$this->_CC_['page'] = "?Page=My Announcement";
		$this->opMessage("reload_page");
		exit;
	}

	/*-----------\
        | add topic |
        \-----------*/
	function addTopic()
	{
		if(!$_SESSION['UserName'])
		{
			$this->opUdfMessage("udf_040"); // login required
			exit;
		}
		$page     = $this->_CC_['Page'];
		$username = $this->_CC_['UserName'];

		$datetime = $this->_CC_['datetime'];

		$q = @$this->BLOG->query("SELECT COUNT(*) FROM blog");
		if ($q === false)
		{
			$this->createDbase("blog","blog");
		}

		$q = $this->BLOG->query("INSERT INTO blog VALUES(NULL, '$page', '0', '0', ".
					 "'$username', '', '', ".
					 "'New Topic', 'Please update this content...', '$datetime')");
	
		$q = $this->BLOG->query("SELECT bid FROM blog WHERE Page='$page' ORDER BY bid DESC");
		list($this->_CC_['bid']) = $q->fetch();
		if(!$this->_CC_['bid'])
		{
			echo "Error in adding new records...";
			exit;
		}
		$this->updateBlog();
		exit;
	}

	/*------------\
        | add comment |
        \------------*/
	function addComment()
	{
		$this->BLOG = new SQLiteDatabase("./users/".$this->_CC_['member']."/blog.dbf"); // user blog database

		$bid      = $this->_CC_['bid'];
		$from     = $this->_CC_['FROM'];
		$topic    = "";
		$content  = sqlite_escape_string(stripslashes($_POST['COMMENT']));
		$website  = $_POST['SITE'];
		$email    = $_POST['EMAIL'];
		$datetime = $this->_CC_['datetime'];
		
		list($page) = explode(".",$this->_CC_['Page']);

		if(!$from || !$content)
		{
			$this->_CC_['vfy'] = 1;
			$this->opMessage("resubmit_post");
			exit;
		}
		if(!$_SESSION['UserName'])
		{
			if($this->checkVerification())
			{
				$this->_CC_['vfy'] = 2;
				$this->opMessage("resubmit_post");
				exit;
			}
		}
		
		$q = $this->BLOG->query("INSERT INTO blog VALUES(NULL, '$page', '$bid', '0', ".
					 "'$from', '$website', '$email', ".
					 "'$Topic', '$content', '$datetime')");
		if ($q === false)
		{
			echo "Database error!";
			exit;
		}

		$q = $this->BLOG->query("SELECT nCmmnts FROM blog WHERE bid='$bid'");
		list($ncmnts) = $q->fetch();
		$ncmnts++;
		$this->BLOG->query("UPDATE blog SET nCmmnts='$ncmnts' WHERE bid='$bid'");
		
		$link = $this->_CC_['page'] = "?Page=".$this->_CC_['PAGE']."&bid=$bid&member=".$this->_CC_['member'];

		$this->MEMBERS->query("INSERT INTO activities VALUES(NULL,'blog','".$this->_CC_['member'].
				      "','$from','added a comment in $page','$link','$datetime')");
	
		$this->opMessage("reload_page");

		exit;
	}

	/*-----------------\
        | update blog/news |
        \-----------------*/
	function updateBlog()
	{
		$q = $this->MEMBERS->query("SELECT Name FROM members WHERE ID='".$_SESSION['UserName']."'");
		list($this->_CC_['name']) = $q->fetch();
		
		if($this->_CC_['delete']) return $this->deleteBlog($this->_CC_['delete']);
		
		if($this->_CC_['utype']=="comment") return $this->addComment();
		
		$bid = $this->_CC_['bid'];
		if(!$bid) return $this->addTopic();
		
		$topic = sqlite_escape_string(stripslashes($_POST['Topic']));
		if(!$topic)
		{
			$q = $this->BLOG->query("SELECT * FROM blog WHERE bid='$bid'");
	
			list($this->_CC_['bid'],$this->_CC_['Page'],$this->_CC_['reply'],$this->_CC_['ncmmnts'],
			     $this->_CC_['UserName'],$this->_CC_['Website'],$this->_CC_['Email'],$this->_CC_['Topic'],
			     $this->_CC_['Content']) = $q->fetch();

			if(!$this->_CC_['bid'])
			{
				echo "Article not found!";
				exit;
			}
			$this->opMessage("update_blog");
			exit;
		}
		$content = sqlite_escape_string(stripslashes($_POST['Content']));
		$page    = $_POST['Page'];
		$email   = $_POST['Email'];
		$website = $_POST['Website'];
		$date    = $this->_CC_['datetime'];

		$q = @$this->BLOG->query("UPDATE blog SET eMail='$email',Website='$website',Topic='$topic',Content='$content',mdate='$date' WHERE bid='$bid'");
		if ($q === false)
		{
			echo "Error updating $page";
			exit;
		}
		$uname = $_SESSION['UserName'];
		$name  = $this->_CC_['name'];
		$PAGE  = $this->_CC_['PAGE'];
		$this->_CC_['page'] = $link = "?Page=".$this->_CC_['PAGE']."&thread=$thread&member=$uname";
		$this->MEMBERS->query("INSERT INTO activities VALUES(NULL,'editnews','$uname','$name','added/updated content in $page','$link','$date')");

		$this->opMessage("close_window");

		exit;
	}
	
	/*------------------\
        | delete blog entry |
        \------------------*/
	function deleteBlog($bid)
	{
		$q = $this->BLOG->query("SELECT Page,Reply FROM blog WHERE bid='$bid'");
		list($page,$reply) = $q->fetch();
		if($reply)
		{
			$q = $this->BLOG->query("SELECT nCmmnts FROM blog WHERE bid='$reply'");
			list($ncmnts) = $q->fetch();
			$ncmnts--;
			$this->BLOG->query("UPDATE blog SET nCmmnts='$ncmnts' WHERE bid='$reply'");
			$id = "&bid=$reply";
		}
		else
		{	
			$this->BLOG->query("DELETE FROM blog WHERE Reply='$bid'");
		}
		$this->BLOG->query("DELETE FROM blog WHERE bid='$bid'");
		
		$uname = $_SESSION['UserName'];
		$name  = $this->_CC_['name'];
		$PAGE  = $this->_CC_['PAGE'];
		//$this->MEMBERS->query("INSERT INTO activities VALUES(NULL,'editnews','$uname','$name',".
		//		      "'deleted an entry in $page','?Page=$PAGE&member=$uname','".$this->_CC_['datetime']."')");
	
		$this->_CC_['page'] = "?Page=$PAGE$id";

		$this->opMessage("reload_page");
		exit;
	}

        /*------------\
        | update menu |
        \------------*/
	function updateMenu()
	{
		if($_REQUEST['addpage'])
		{
			$this->addMenuItem($_POST['main'],$_POST['mname'],$_POST['addpage']);
			exit;
		}
		if(isset($_REQUEST['edit']))
		{
			$this->updateMenuItem();
			exit;
		}
		if($_REQUEST['mvup']) return $this->moveRecord("UDB",$this->_CC_['mname'],$this->_CC_['mvup']);
		
		if($_POST['Save'])
		{
			if($_POST['Save']=="Close")
			{
				$this->opMessage("lytebox_close");
				exit;
			}
			$this->deleteMenu();
			exit;
		}
		
		list($set,$form) = explode("^^^^^",$this->getTplValue("frms","odcms_menu"),2);
		$this->opUdfMsgs($set);
		
		$menu = $this->_CC_['mname'];
		if(!$menu) $menu = "menu1";
		
		$size = $this->getMenuList($menu,$menu);

		$ptype = $this->_CC_['spage'];
		$ix = 0;
                while($this->_CC_[$menu."Name_$ix"])
                {
			$this->_CC_['NAME'] = trim($this->_CC_[$menu."Name_$ix"]);
			if($this->_CC_['NAME'] == "") break;

			$this->_CC_['THEME'] = trim($this->_CC_[$menu."Theme_$ix"]);
			$this->getSelectList("NA",$this->_CC_['THEME']);

			$this->_CC_['MID'] = $mid = $this->_CC_[$menu."MID_$ix"];
			
			$this->_CC_['TITLE']  = trim($this->_CC_[$menu."Title_$ix"]);
			$this->_CC_['ATTRS']  = preg_replace("/\"/","'",$this->_CC_[$menu."Attrs_$ix"]);
			$this->_CC_['META']  .= $this->_CC_[$menu."Meta_$ix"];
			$this->_CC_['HIDE']   = $this->_CC_[$menu."Hide_$ix"];
			$this->_CC_['DESC']   = $this->_CC_[$menu."Desc_$ix"];
			$this->_CC_['MAIN']   = $this->_CC_[$menu."Main_$ix"];
			$this->_CC_['TYPE']   = $this->_CC_[$menu."Type_$ix"];
			if(!$this->_CC_['TYPE']) $this->_CC_['TYPE'] = "Document";

			if($this->_CC_['TYPE']=="Document" || $this->_CC_['TYPE']=="Listing" || $this->_CC_['TYPE']=="Blog" || $this->_CC_['TYPE']=="Table")
			{
				$ptype = 0;
				$stype = "";
				$this->_CC_['SubPage'] = "<a title='Add/Update Sub Pages' href='?Update=menu&mname=".
					$this->_CC_['NAME']."&main=$menu&spage=0'>SubPage</a>";
			}
			else
			{
				//$ptype = 1;
				$this->_CC_['SubPage'] = "";
			}

			if($ix)
			{
				$this->_CC_['MoveUp'] = "<a href='?Update=menu&mname=$menu&mvup=$mid$stype'>MoveUp</a>";
			}
			//$this->_CC_['Edit'] = "<a href='?Update=menu&mname=$menu&edit=$ix$stype'>Edit</a>";
			$ix++;

			$this->_CC_['content'] .= $this->subString($this->_CC_['input'])."\n";
		}
		$this->_CC_['NUM'] = $ix;
		if(!$ptype || $menu == "menu1" || $menu == "menu2")
		{
			$fmt = $this->_CC_['AddPage'];
		}
		elseif($ptype=="1")
		{
			$fmt = $this->_CC_['AddGallery'];
		}
		//else $fmt = $this->_CC_['AddArticle'];

		$this->_CC_['AddContent'] = $this->subString($fmt)."\n";

		$this->opUdfMsgs($form);
		
		exit;

	}
				
        /*-----------------\
        | update menu item |
        \-----------------*/
	function updateMenuItem()
	{
		$rnum  = $_REQUEST['edit'];
		$table = preg_replace("/ /","_",$_REQUEST['menu']);

		if(is_numeric($table)) $table = "t_$table";
		
		if(isset($_POST['edit'])) return $this->saveMenuItem($table,$_POST['edit']);
				
		$q = @$this->UDB->query("SELECT * FROM $table WHERE mid='$rnum'");
		if ($q === false)
		{
			echo "Error getting id number $rnum from table $table";
			exit;
		}
		list($this->_CC_['Name'],$this->_CC_['MID'],$this->_CC_['Main'],
		     $this->_CC_['Type'],$this->_CC_['Hide'],
		     $this->_CC_['Theme'],$this->_CC_['Title'],
		     $this->_CC_['Attrs'],$this->_CC_['Meta'],
		     $this->_CC_['Desc']) = $q->fetch();

		$this->getSelectList("NA",$this->_CC_['Theme']);
		if($this->_CC_['Hide']) $this->_CC_['Hide'] = "checked";
		$this->_CC_['Desc'] = preg_replace("/<\/textarea/","&lt;/textarea",$this->_CC_['Desc']);
		$this->_CC_['Attrs'] = preg_replace("/\"/","'",$this->_CC_['Attrs']);

		$theme = $this->_CC_['Theme'];
		if(!$theme) $theme = $this->_CC_['template'];
		list($theme,$sub) = explode(".",$theme);
		if($sub) $theme = "$theme/$sub";
		list($path) = explode("\n",@file_get_contents("../templates/$theme.tpl"));

		if(!$path)
		{
			
		}
		
		list($tmp,$path) = explode("=",$path);
		$this->_CC_['path'] = trim($path);

		$this->opForm("menu_update");

		exit;
	}
		
        /*---------------\
        | save menu item |
        \---------------*/
	function saveMenuItem($table,$id)
	{
		if($_POST['delete'])
		{
			//$this->deleteMenu($table);
			echo "Function disabled";
			exit;
		}
		if($_POST['Theme']=="NONE") $_POST['Theme'] = "";
		$set = "Desc='".sqlite_escape_string(stripslashes($_POST['Desc']))."', ".
		       "Attrs='".sqlite_escape_string(stripslashes($_POST['Attrs']))."', ".
		       "Meta='".sqlite_escape_string(stripslashes($_POST['Meta']))."', ".
		       "Theme='".$_POST['Theme']."', ".
		       "Title='".sqlite_escape_string(stripslashes($_POST['Title']))."', ".
		       "Main='".sqlite_escape_string(stripslashes($_POST['Main']))."', ".
		       "Hide='".$_POST['Hide']."'";

		if($_POST['Rename'])
		{
			if(! $this->renameMemberFile($_POST['name'],$_POST['Rename']))
			{
				$set .= ", Name='".$_POST['Rename']."'";
			}
		}

		$q = $this->UDB->query("UPDATE $table SET $set WHERE mid='$id'");
		if ($q === false)
		{
			echo "Error updating $table where ID=$id";
			exit;
		}
		
		$q = @$this->UDB->query("SELECT Name,Type,Hide FROM $table WHERE mid='$id'");
		list($pname,$type,$hide) = $q->fetch();

		if($_POST['lytebox']) $this->opMessage("lytebox_close");
		$this->opMessage("close_window");
		exit;
	}


        /*-----------------\
        | save member data |
        \-----------------*/
	function saveMemberData($file_name,$data)
	{
		$fp = @fopen("./users/$this->username/$file_name","w");

		if(!$fp )
		{
			$this->_CC_['FileName'] = $file_name;
			$this->opUdfMessage("udf_031"); // Can't write to member data file
			exit;
		}
		$data = stripslashes($data);
		//$data = preg_replace("/\012\015/","\015",$data);
		
		fwrite($fp, $data);
		fclose($fp);
	}

	/*------------\
        | delete menu |
        \------------*/
	function deleteMenu()
	{
		$table = preg_replace("/ /","_",$_REQUEST['mname']);

		$ndel = 0;;
		for($ix=0;$ix<=$_POST['delete'];$ix++)
		{
			if($_POST["delete$ix"]!="on") continue;
			$q = @$this->UDB->query("SELECT Name,Type,Main FROM $table WHERE mid='$ix'");
			list($name,$type,$main) = $q->fetch();
			//echo "$ix: ($type) ($main) ";
			if($type=="Gallery") $this->deleteGallery($name);
			if($type=="Blog")
			{
				$this->BLOG->query("DELETE FROM blog WHERE Page='$name'");
			}
			$name = sqlite_escape_string(stripslashes($name));
			echo "DELETE FROM $table WHERE Name='$name'<br />";
			$this->UDB->query("DELETE FROM $table WHERE Name='$name'");
			$this->UDB->query("DELETE FROM Document WHERE Name='$name'");
			$this->_CC_['error'] = "&error=$name deleted from $table!";
			if($type=="Table")
			{
				$this->DESIGNS = new SQLiteDatabase("./designs.dbf");
				$this->DESIGNS->query("DROP TABLE $name");
			}
			$ndel++;
		}
		if($ndel) $this->_CC_['error'] = "&error=$ndel file(s) deleted";
		$this->opMessage("reload_menu");
		exit;
	}
	
        /*--------------\
        | add menu item |
        \--------------*/
	function addMenuItem($main,$mname,$newpage)
	{
		$newpage = preg_replace("/'/","`",$newpage);
		$newpage = preg_replace("/#/","*",$newpage);
		$newpage = sqlite_escape_string(stripslashes(trim($newpage)));

		$mname   = preg_replace("/ /","_",$mname);
		
		if(is_numeric($mname)) $mname = "t_$mname";
		$this->_CC_['pname'] = $newpage = preg_replace("/\./","_",$newpage);
		if($this->addMemberFile($_POST['ptype'],$newpage))
		{
			$this->opMessage("reload_menu");
			exit;
		}
		
		$q = @$this->UDB->query("SELECT Name FROM $mname WHERE Name='$newpage'");
		if ($q === false)
		{
			$this->createDbase("menu",$mname);
		}
		$ptype = $_POST['ptype'];
		if(!$ptype) $ptype = "Document";
		
		if($ptype=="Table") $title = "table_content";
	        else $title = $newpage;

		$q = $this->UDB->query("SELECT mid FROM $mname ORDER BY mid DESC");
		if($q)
		{
			list($mid) = $q->fetch();
		}
		$mid++;
		$dtime = $this->_CC_['datetime'];
		$this->UDB->query("INSERT INTO $mname VALUES('$newpage','$mid','$mname^$main','$ptype','','','$title','','','','$dtime')");
		if($ptype == "Blog")
		{
			$q = $this->BLOG->query("SELECT COUNT(*) FROM blog");
			if ($q === false)
			{
				$this->createDbase("blog","blog");
			}
			$this->BLOG->query("INSERT INTO blog VALUES(NULL, '$newpage', '0', '0', ".
					 "'$this->username', '', '', ".
					 "'First Topic', 'Please update this content and the header...', '$dtime')");
		}
		elseif($ptype=="Forum")
		{
			$q = @$this->FORUM->query("SELECT COUNT(*) FROM $newpage");
			if ($q === false)
			{
				$this->createDbase("forum",$newpage);
			}
		}
		//if($_POST['ptype'] == "create") return; // create user
		
		$this->opMessage("reload_menu");
		
		exit;
	}

        /*-----------------\
        | add gallery page |
        \-----------------*/
	function addGallery($album)
	{
		$q = @$this->UDB->query("SELECT Album FROM Albums WHERE Album='$album'");
		if ($q === false)
		{
			$this->createDbase("album","Albums");
		}
		else
		{
			list($name) = $q->fetch();
			if($name==$album)
			{
				$this->_CC_['error'] = "&error=$album exists!";
				return 1;
			}
		}
		$this->makeDirectory("./users/$this->username/images/$album");
	}

        /*--------------------\
        | save member content |
        \--------------------*/
	function saveMemberContent($page)
	{
		$header  = sqlite_escape_string(stripslashes($_POST['header']));
		$content = sqlite_escape_string(stripslashes($_POST['content']));
		$page    = sqlite_escape_string(stripslashes($page));

		$q = @$this->UDB->query("UPDATE Document SET Header='$header', Content='$content', mdate='".
					$this->_CC_['datetime']."' WHERE Name='$page'");

		if ($q === false)
		{
			echo "Error updating $page";
			exit;
		}
		if($this->_CC_['USITE']!="_main" && $this->username == "admin")
		{
			$q  = new SQLiteDatabase("../_main/members.dbf"); // main site members database
			$id = substr($this->_CC_['USITE'], 1);
			$q->query("UPDATE members SET mDate='".$this->_CC_['datetime']."' WHERE ID='$id'");
		}
		$this->opMessage("lytebox_close");
		
		exit;
	}
	
        /*----------------\
        | add member file |
        \----------------*/
	function addMemberFile($ptype,$page)
	{
		switch($ptype)
		{
			case 'Gallery':
				$this->addGallery($page);
			case 'Document':
			case 'Blog':
			case 'Table':
			case 'redirect':
			case 'Forum':
			case 'Listings':
			case 'Local':
				return $this->addDocument($ptype,$page);
				break;
				
			default:
				$this->_CC_['error'] = "&error=Invalid Type";
				return 1;
		}
		return 0;
	}

        /*------------------\
        | add document page |
        \------------------*/
	function addDocument($ptype,$page)
	{
		$q = @$this->UDB->query("SELECT name FROM Document WHERE Name='$page'");
		if($q === false)
		{
			$this->_CC_['error'] = "&error=Create $page failed -- unable to open Document table!";
			return 1;
		}
		list($name) = $q->fetch();
		if($name)
		{
			$this->_CC_['error'] = "&error=$page is already used!";
			return 1;
		}

		$q = @$this->UDB->query("SELECT cid FROM Document ORDER BY cid DESC");
		list($cid) = $q->fetch();
		$cid++;
		$q = $this->UDB->query("INSERT INTO Document VALUES('$page','$cid','$ptype','$page',".
				       "'Please update the content...','".$this->_CC_['datetime']."')");
		
		$this->_CC_['error'] = "&error=$page added";
		return 0;
	}
	
        /*-------------------\
        | rename member file |
        \-------------------*/
	function renameMemberFile($old_name,$new_name)
	{
		$q = @$this->UDB->query("SELECT name FROM Document WHERE Name='$new_name'");
		if($q === false)
		{
			$this->_CC_['error'] = "&error=Unable to open Document table!";
			return 1;
		}
		list($name) = $q->fetch();
		if($name)
		{
			$this->_CC_['error'] = "&error=$name is already used!";
			return 1;
		}
		$q = @$this->UDB->query("UPDATE Document SET Name='$new_name', mdate='".
					$this->_CC_['datetime']."' WHERE Name='$old_name'");
		if ($q === false)
		{
			$this->_CC_['error'] = "&error=Rename $old_name to $new_name failed";
			return 1;
		}
		$this->_CC_['status'] .= "$old_name is renamed to $new_name.<br />";
		return 0;
	}

        /*---------------\
        | add odcms data |
        \---------------*/
	function addCmsData()
	{
		$tname = trim($_REQUEST['add']);
		$table = trim($this->_CC_['dtype']);
		$q = @$this->TEMPLATES->query("SELECT COUNT(*) FROM $table WHERE name='$tname'");

		list($total) = $q->fetch();
		if($total)
		{
			$this->_CC_['tpl'] = $tname;
			$this->opUdfMessage("udf_015"); //<p>Template name ({tpl}) is already used.</p>
			exit;
		}
		$q = @$this->TEMPLATES->query("SELECT tid FROM $table ORDER BY tid DESC");
		list($lid) = $q->fetch();
		$lid++;

		$q = $this->TEMPLATES->query("INSERT INTO $table VALUES('$tname','$lid','$tname Description...','$tname Value...','".
					$this->_CC_['datetime']."')");
		if ($q === false)
		{
			echo "Error updating table $table";
			exit;
		}
		//echo "$tname added";
		$this->_CC_['page'] = "?Update=odcms&dtype=".$this->_CC_['dtype'];
		$this->opMessage("reload_page");
		exit;
	}
	
        /*------------------\
        | delete odcms data |
        \------------------*/
	function deleteCmsData($table,$tname)
	{
		$q = @$this->TEMPLATES->query("DELETE FROM $table WHERE name='$tname'");
		if ($q === false)
		{
			echo "Error deleting $tname from $table";
			exit;
		}
		//echo "$tname deleted";
		return;
	}
	
        /*------------------\
        | update odcms data |
        \------------------*/
	function updateCmsData($table,$tname)
	{
		$desc  = sqlite_escape_string($_POST['tdesc']);
		$data  = sqlite_escape_string($_POST['tdata']);
		$mdate = $this->_CC_['datetime'];
		$q = @$this->TEMPLATES->query("UPDATE $table SET desc='$desc', value='$data', mdate='$mdate' WHERE name='$tname'");
		if ($q === false)
		{
			echo "Error updating $table where name=$tname";
			exit;
		}
		echo "$tname upated";
		$this->opMessage("close_window");
		exit;
	}

        /*-----------------------\
        | update odCMS templates |
        \-----------------------*/
	function updateCmsTemplates($table)
	{
		if($_REQUEST['mvup'])
		{
			$this->moveRecord("SQL",$_REQUEST['dtype'],$_REQUEST['mvup']);
			exit;
		}

		if(!$_GET['editor'])
		{
			$this->getCmsTemplateList($table,1);
			$this->opForm("odcms");
			exit;
		}
		$tid = $_REQUEST['tpl'];
		$q = $this->TEMPLATES->query("SELECT * FROM $table WHERE tid = '$tid'");
		list($name,$id,$desc,$value,$mdate) = $q->fetch();

		$this->_CC_['tdesc'] = preg_replace("/<\/textarea/","&lt;/textarea",$desc);
		$this->_CC_['tdata'] = preg_replace("/<\/textarea/","&lt;/textarea",$value);
		$this->_CC_['tname'] = stripslashes($name);
		$this->_CC_['tdesc'] = stripslashes($this->_CC_['tdesc']);
		$this->_CC_['tdata'] = stripslashes($this->_CC_['tdata']);
		
		$this->opForm("odcms_update");
		exit;
        }

        /*------------\
        | move record |
        \------------*/
	function moveRecord($dbase,$table,$rnum)
	{
		$table = preg_replace("/ /","_",$table);
		if(is_numeric($table)) $table = "t_$table";
		if($dbase=="UDB")
		{
			$q = $this->UDB->query("SELECT name,mid FROM $table WHERE mid < '$rnum' ORDER BY mid DESC LIMIT 1");
		}
		else
		{
			$q = $this->TEMPLATES->query("SELECT name,tid FROM $table WHERE tid < '$rnum' ORDER BY tid DESC LIMIT 1");
		}
		if ($q === false)
		{
			echo "Error getting id number $rnum from table $table";
			exit;
		}
		
		list($name,$pid) = $q->fetch(); // previous record name and id number
		
		if($dbase=="UDB")
		{
			$q = $this->UDB->query("UPDATE $table SET mid='$pid' WHERE mid='$rnum'");
		}
		else
		{
			$q = $this->TEMPLATES->query("UPDATE $table SET tid='$pid' WHERE tid='$rnum'");
		}
		if ($q === false)
		{
			echo "Error updating id number $rnum for table $table";
			exit;
		}
		
		if($dbase=="UDB")
		{
			$q = $this->UDB->query("UPDATE $table SET mid='$rnum' WHERE name='$name'");
		}
		else
		{
			$q = $this->TEMPLATES->query("UPDATE $table SET tid='$rnum' WHERE name='$name'");
		}
		if ($q === false)
		{
			echo "Error updating id number $rnum for table $table";
			exit;
		}
		
		if($dbase=="UDB")
		{
			$stype = "";
			if($this->_CC_['add']) $stype = "&stype=".$this->_CC_['add'];
			elseif($this->_CC_['stype']) $stype = "&stype=".$this->_CC_['stype'];

			$this->_CC_['mname'] = "$table";
			$this->opMessage("reload_menu");
		}
		else
		{
			$this->_CC_['page'] = "?Update=odcms&dtype=".$this->_CC_['dtype'];
			$this->opMessage("reload_page");
		}
		exit;
	}


	/*------------------\
        |  unlink Recursive |
        \------------------*/
	function unlinkRecursive($dir)
	{
		if(!$dh = @opendir($dir))
		{
			return;
		}
		while (false !== ($obj = readdir($dh)))
		{
			if($obj == '.' || $obj == '..')
			{
				continue;
			}

			if (!@unlink($dir . '/' . $obj))
			{
				unlinkRecursive($dir.'/'.$obj);
			}
		}

		closedir($dh);
   
		@rmdir($dir);

		return;
	}
	
}
?>
